package com.imooc.luckymoney.handle;

import com.imooc.luckymoney.entity.Result;
import com.imooc.luckymoney.enums.ResultEnum;
import com.imooc.luckymoney.exception.LuckymoneyException;
import com.imooc.luckymoney.exception.LuckymoneyFormException;
import com.imooc.luckymoney.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

@ControllerAdvice
public class ExceptionHandle {

    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception e){
        if (e instanceof LuckymoneyFormException) {
            return ResultUtil.formError((LuckymoneyFormException)e);
        }else if(e instanceof LuckymoneyException){
            return ResultUtil.error((LuckymoneyException) e);
        }else if(e instanceof MethodArgumentTypeMismatchException){
            return ResultUtil.formError(new LuckymoneyFormException(ResultEnum.ID_MISMATCH_ERROR,"参数输入有误请重试"));
        }else {
            logger.error("【系统异常】{}",e);
            return ResultUtil.error(new LuckymoneyException(ResultEnum.UNKNOWN_ERROR));
        }
    }

}
